class Cells:

    def __init__(self, matrix):
        self.width = len(matrix[0])
        self.height = len(matrix)
        self.age = 0

        self.cells = matrix

    def run(self):
        import time
        t = time.clock()
        self.age += 1

        nextMatrix = []

        for y in range(self.height):
            nextMatrix.append([])
            for x in range(self.width):
                nextMatrix[-1].append(self.checkFuture((x,y)))
        self.cells = nextMatrix

        print "Time to run", time.clock() - t


    def listNeighbours(self,(x,y)):

        def getNext((i,j)):
            return self.cells[y+j][x+i]


        neighbours = []

        if not self.edge((x,y)):
            adjecent = [(-1,-1),(-1,0),(-1,1),(0,-1),(0,1),(1,-1),(1,0),(1,1)]
            neighbours = map(getNext, adjecent)
            
        return neighbours

    def cellprint(self):
        print "The Cells are %d iterations old." %self.age
        for y in range(self.height):
            print self.cells[y]
        print  ""

    def edge(self, (x,y)):
        if (x == self.width - 1 or x == 0):
            return True
        elif (y == self.height - 1 or y == 0):
            return True
        else:
            return False

    def checkFuture(self,(x,y)): # This implements the rules of the game of life.
        if self.cells[y][x]:
            alive = 0
            for neighbour in self.listNeighbours((x,y)):
                if neighbour == 1:
                    alive += 1
            if alive < 2:
                return 0
            elif alive > 3:
                return 0
            else:
                return 1
        else:
            alive = 0
            for neighbour in self.listNeighbours((x,y)):
                if neighbour == 1:
                    alive += 1
            if alive == 3:
                return 1
            return 0


def StartGame(matrix):
    return Cells(matrix)